package com.omt.tarjimdinek.util;

import java.io.UnsupportedEncodingException;
import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;

import org.apache.log4j.Logger;
import org.omnifaces.eventlistener.DefaultPhaseListener;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.web.WebAttributes;
import org.springframework.util.StringUtils;

import com.omt.tarjimdinek.util.LogPhaseListener;

public class LoginErrorPhaseListener extends DefaultPhaseListener {

	private static final long serialVersionUID = 1L;

	private static final Logger log = Logger.getLogger(LoginErrorPhaseListener.class);

	private ResourceBundle message = ResourceBundle.getBundle("localization.messages");
	
	@Override
	public void beforePhase(final PhaseEvent arg0) {

		Exception e = (Exception) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
		                .get(WebAttributes.AUTHENTICATION_EXCEPTION);
		
		if (e instanceof BadCredentialsException) {
			
			FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
			                .put(WebAttributes.AUTHENTICATION_EXCEPTION, null);
			addMessage(FacesMessage.SEVERITY_ERROR, "main.connection.title.error", "main.connection.body.error");
		}
	}

	/**
	 * Add a message to faces context
	 * @param aTitle
	 * @param aContent
	 */
	public void addMessage(Severity aSeverity, String aTitle, String aContent) {
		
		String lTitle = aTitle;
		Severity lSeverity = FacesMessage.SEVERITY_INFO;
		
		if(aSeverity != null){
			lSeverity = aSeverity;
		}
		if(aSeverity.equals(FacesMessage.SEVERITY_ERROR) && !StringUtils.hasLength(aTitle)) {
			lTitle = "main.subscription.defaultTitle.error";
		}
		
		String lContent = message.getString(aContent);
		lTitle = message.getString(lTitle);
		try {
			lContent = new String(lContent.getBytes("ISO-8859-1"), "UTF-8");
			lTitle = new String(lTitle.getBytes("ISO-8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			lContent = message.getString(aContent);
		}
		
		FacesContext.getCurrentInstance().addMessage(null, 
				new FacesMessage(lSeverity, lTitle, lContent)); 
	}
	
	public LoginErrorPhaseListener() {

		super(PhaseId.ANY_PHASE);
	}

	@Override
	public void afterPhase(PhaseEvent event) {

		if (log.isDebugEnabled()) {
			log.debug(event.getPhaseId());
		}
	}

}
